package org.szy.monitor.task;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import com.mybatisflex.core.query.QueryWrapper;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.scheduling.annotation.Scheduled;
import org.szy.core.common.enums.CommonStatusEnum;
import org.szy.core.event.monitor.contant.OnlineConstants;
import org.szy.monitor.entity.UserOnline;
import org.szy.monitor.service.UserOnlineService;

import java.util.Date;
import java.util.List;

import static org.szy.monitor.entity.table.UserOnlineTableDef.USER_ONLINE;

/**
 * 在线用户定时器
 *
 * @author 孙志阳
 * @date 2023-07-05
 * @since 1.0.0
 **/
@Component
public class UserOnlineTask {

    @Inject
    private UserOnlineService userOnlineService;

    private QueryWrapper buildOfflineQuery(Date date) {

        return QueryWrapper.create()
                .select("id", "token")
                .where(USER_ONLINE.STATUS.eq(CommonStatusEnum.ENABLE.getKey()));
    }

    private void doOfflines() {
        Date now = new Date();

        QueryWrapper query = this.buildOfflineQuery(now);

        List<UserOnline> onlineList = this.userOnlineService.list(query);

        for (UserOnline online : onlineList) {
            SaSession session = StpUtil.getStpLogic().getTokenSessionByToken(online.getToken(), false);
            if (ObjUtil.isNotNull(session)) {
                Date expDate = (Date) session.get(OnlineConstants.EXPIRATION_DATETIME);
                if (ObjUtil.isNotNull(expDate) && DateUtil.compare(now, expDate) < 0) {
                    continue;
                }
            }
            online.setStatus(CommonStatusEnum.DEACTIVATE.getKey());
            this.userOnlineService.updateById(online, true);
        }
    }

    @Scheduled(cron = "0 0/20 * * * ?")
    public void processOfflines() {
        this.doOfflines();
    }
}
